package cn.hpclub.server.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.ext.plugin.shiro.ShiroMethod;
import com.jfinal.kit.StrKit;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.util.SystemConfigUtil;

public class AdminInterceptor implements Interceptor{
    public void intercept(Invocation ai){
        Controller controller = ai.getController();
        SystemConfig systemConfig = SystemConfigUtil.getSystemConfig();
        controller.setAttr("systemConfig", systemConfig);
        controller.setAttr("base", controller.getRequest().getContextPath());

        if(ShiroMethod.notAuthenticated()){
            String ajax = ai.getController().getRequest().getHeader("X-Requested-With");
            if("XMLHttpRequest".equals(ajax)){
                controller.renderJson(new JSONObject().put("status", 401).put("url", "/admin/login")
                        .put("message", "会话超时，请重新登录系统！").toString());
            } else{
                controller.redirect("/admin/login");
            }
        } else{
            if(!validCsrfAddress(ai.getController().getRequest())){
                ai.getController().renderError(401);
            } else{
                ai.invoke();
            }
        }
    }

    public boolean validCsrfAddress(HttpServletRequest request){
        String requestURI = request.getRequestURI();
        if(!StrKit.isBlank(requestURI) && requestURI.endsWith("/ueditor/upload")){
            return true;
        }
        String ctx = request.getServerName();
        String referer = request.getHeader("Referer");
        if(StringUtils.isEmpty(referer)){
            return false;
        }
        if(referer.contains(ctx)){
            return true;
        }
        return false;
    }
}
